# 此脚本主要用于爬取别的网站上的图片插入自己的数据库
import requests
import json


def get_images_json():
    url = 'https://www.duitang.com/napi/index/hot/'

    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36 Edg/88.0.705.63"
    }

    params = {
        "include_fields": "top_comments,is_root,source_link,item,buyable,root_id,status,like_count,sender,album",
        "limit": 100,
        "start": 1,
        "_": "1612939423463"
    }

    session = requests.session()
    session.get("https://www.duitang.com/")
    res = session.get(url, params=params, headers=headers)
    with open("./image_data.json", "wb") as file:
        file.write(res.content)


def add_images_from_json():
    def do_post_image(json_data):
        url = "http://localhost:7000/image-serv/image"
        session = requests.session()
        res = session.post(url, json=json_data)
        print(res.text)

    image_info_list = []
    with open("./image_data.json", "r", encoding="utf-8") as file:
        json_info = json.load(file)
        object_list = json_info["data"]["object_list"]
        for object_item in object_list:
            _info = {
                "title": object_item["album"]["name"],
                "description": object_item["msg"],
                "createdBy": 1,
                "url": object_item["photo"]["path"],
                "label": "堆糖"
            }
            image_info_list.append(_info)
    for info_item in image_info_list:
        do_post_image(info_item)


if __name__ == "__main__":
    add_images_from_json()
